<!-- 模板详情 -->
<template>
  <div class="template-dialog">
    <div class="template-menu">
      <span class="template-title"> 区域组件 </span>
      <div id="accordion">
        <!-- 左侧菜单 -->
        <!-- { title: '主播区', name: '主播区', prop: 'Main' }, -->
        <a
          v-for="(item, idx) in menuItem"
          :key="idx"
          href="javascript:;"
          @click="addWidgetInfo(item)"
          index="0"
          :name="item.prop"
          class="addWiget"
          :title="item.title"
          >{{ item.name }}</a>
      </div>
    </div>
    <div class="template-main">
      <div class="template-condition">
        <el-form style="flex-grow:1; display:flex;" :inline="true" ref="editorFormRef" size="small">
          <el-form-item style="flex-grow:1;" label="模板名称">
            <el-input
              id="name"
              v-model="templateName"
              placeholder="请输入模板名称"
              autocomplete="off"
              :show-word-limit="false"
              clearable
              style="width: 330px"
              maxlength="20"
            ></el-input>
          </el-form-item>
          <el-form-item style="margin-right: 0 !important;">
            <bs-confirm-button-icon @click.native="doSubmitPreCheck"></bs-confirm-button-icon>
            <bs-original-size-button-icon v-if="!originalState" :show-icon="false" @click.native="originalSize"></bs-original-size-button-icon>
            <el-button v-if="originalState" type="primary" size="small" @click="reductionSize">缩放尺寸</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 右键删除菜单 -->
      <delete-context-menu></delete-context-menu>
      <!-- 添加的元素 -->
      <elements></elements>
      <div
        :class="[className]"
        :style="[computedStyle]"
        class="template-main-wrapper-original"
        v-if="originalState"
      >
        <div
          :style="[computedInnerStyle]"
          class="compont"
          id="compont"
          ref="capture"
        ></div>
      </div>
      <div
        :class="[className]"
        :style="[computedStyle]"
        class="template-main-wrapper"
        v-else
      >
        <div
          :style="[computedInnerStyle]"
          class="compont"
          id="compont"
          ref="capture"
        ></div>
      </div>
    </div>
    <div class="template-attr">
      <model-info></model-info>
    </div>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
import $ from 'jquery'
import DeleteContextMenu from './TemplateComponents/DeleteContextMenu'
import Elements from './TemplateComponents/Elements'
import ModelInfo from './TemplateComponents/ModelInfo'
import { TemplateOptions } from '@/mixins/Template.js'
import moment from 'moment'
moment.locale('zh-cn')
import { deepClone } from '@/utils/index'
import { HashMap } from '@/utils/hashmap'

const width = 4000
const height = 4000
const templateFormData = {
  title: '模板',
  showArea: 'main',
  formData: {
    showType: '',
    name: '',
    type: `4000*4000`,
    X: 0,
    Y: 0,
    W: width,
    H: height,
    Z: 0,
    width: width,
    height: height,
    bgfile: '',
    province: '11',
    city: '1100',
    weatherStyle: 1,
    switchTime: 10,
    clockModel: 'Digital',
    clockTimeFormat: '1',
    clockFont: 0,
    clockFontsize: '48',
    clockFontColor: '#FFFFFF',
    timerType: 'Elapse',
    link: '1',
    timerFont: 0,
    timerFontsize: '48',
    timerFontColor: '#FFFFFF',
    timerEndDate: moment(new Date()).format('YYYY-MM-DD'),
    timerEndTime: moment(new Date()).format('00:00:00'),
    weatherAttr: [],
    folderId: 0,
    ownerUserId: 0,
    anchorAvl: 0,
    videoAvl: 0,
    audioAvl: 0
  }
}
export default {
  data() {
    return {
      widgetData: {},
      wrapperWidth: 560,
      wrapperHeight: 560,
      templateOpts: {
        width: width,
        height: height,
      },
      iwidthPercent: 0,
      iheightPercent: 0,
      discardIds: '',
      templateName: '',
      attrForm: deepClone(templateFormData),
      loading: null,
      menuItem: [
        { title: '全屏底色,可添加图片或纯色', name: '背景区', prop: 'Background' },
        { title: '主播区', name: '主播区', prop: 'Main' },
        { title: '综合区', name: '综合区', prop: 'Mixed' },
        { title: '图文区', name: '图文区', prop: 'ImageText' },
        // { title: '网页区', name: '网页区', prop: 'Web' },
        { title: '滚动条', name: '滚动条', prop: 'Scroll' },
        { title: '音频区', name: '音频区', prop: 'Audio' },
        { title: '天气区', name: '天气区', prop: 'Weather' },
        { title: '时钟区', name: '时钟区', prop: 'Clock' },
        { title: '计时区', name: '计时区', prop: 'Timer' },
        { title: '扩展区', name: '扩展区', prop: 'Extension' }
      ],
      originalState: false,
      maxavl: 3
    }
  },
  mixins: [TemplateOptions],
  provide() {
    return {
      attrDataInfo: this.attrForm
    }
  },
  props: {
    className: {
      type: String,
      default: '',
    },
    twidgetData: {
      type: Object,
      default: () => {},
    }
  },
  computed: {
    computedStyle() {
      let w = this.wrapperWidth
      let h = this.wrapperHeight
      if (typeof w === 'number') {
        w = isNaN(w) ? '' : `${w}px`
      }
      if (typeof h === 'number') {
        h = isNaN(h) ? '' : `${h}px`
      }
      let styles = {}
      if (w) styles.width = w
      if (h) styles.height = h

      return styles
    },
    computedInnerStyle() {
      const {width, height} = this.templateOpts // 现实模版宽高
      let {width: wrapWidth, height: wrapHeight} = this.computedStyle // 容器宽高
      wrapWidth = Number(wrapWidth.replace('px', ''))
      wrapHeight = Number(wrapHeight.replace('px', ''))

      let styleWidth;                 // 最终模版在容器的宽
      let styleHeight;                // 最终模版在容器的高
      let ratio;                      // 缩放比
    
      let wrapRatio = width / height
      if(wrapRatio > 1) {
        ratio = wrapWidth / width
        styleWidth = `${wrapWidth}px`
        styleHeight = Math.round(height * ratio) + 'px'
      }else if(wrapRatio < 1) {
        ratio = wrapHeight / height
        styleWidth =  Math.round(width * ratio) + 'px'
        styleHeight = `${wrapHeight}px`
      } else {
        ratio = wrapWidth / width
        styleWidth = `${wrapWidth}px`
        styleHeight = `${wrapHeight}px`
      }
      this.$nextTick(() => {
        this.iwidthPercent = ratio
        this.iheightPercent = ratio
        // 舞台已初始化好
        // 开始塞入组件
        this.layoutInit()
      })

      return {
        width: styleWidth,
        height: styleHeight
      }
    },
  },
  components: {
    // eslint-disable-next-line vue/no-unused-components
    html2canvas,
    DeleteContextMenu,
    Elements,
    ModelInfo,
  },
  mounted() {
    this.$nextTick(function () {
      if(this.twidgetData) {
        this.twidget = null
        this.folderId = this.twidgetData.folderId
        this.ownerUserId = this.twidgetData.ownerUserId
        this.attrForm.formData = {
          ...deepClone(templateFormData.formData),
          ...this.twidgetData
        }
        if(this.twidgetData.argus) {
          const json = JSON.parse(this.twidgetData.argus)
          this.twidget = json
          this.initAttr(json)
        }
        this.templateOpts = {
          width: this.attrForm.formData.width,
          height: this.attrForm.formData.height
        }
        this.templateName = this.twidgetData.name ? this.twidgetData.name.replace('.tpl', '') : ''
      }
      this.layoutInit()
      const that = this
      $(".template-attr").on("click", function(e) {
        if(e.target.className === 'template-attr') {
          that.showResolution()
          e.stopPropagation()
        }
      })
      this.showResolution()
    })
  },
  created() {
    this.$eventBus.$on('changeResolution', this.changeResolution)
    this.$eventBus.$on('changeAttr', this.changeAttr)
  },
  beforeDestroy() {
    this.$eventBus.$off('changeResolution')
    this.$eventBus.$off('changeAttr')
  },
  watch: {
    twidgetData(val) {
      if(val) {
        this.twidget = null
        this.folderId = val.folderId
        this.ownerUserId = val.ownerUserId
        this.attrForm.formData = {
          ...deepClone(templateFormData.formData),
          ...val
        }
        if(val.argus) {
          const json = JSON.parse(val.argus)
          this.twidget = json
          this.initAttr(json)
        }
        console.log('change twidgetData' , this.attrForm)
        this.templateName = val.name? val.name.replace('.tpl', '') : ''
        this.templateOpts = {
          width: this.attrForm.formData.width,
          height: this.attrForm.formData.height
        }
      }
      this.layoutInit()
      this.showResolution()
    }
  },
  methods: {
    // 初始化
    initAttr(json) {
      json.forEach(item => {
        let val
        if(item.clockAttr) {
          val = item.clockAttr
          this.attrForm.formData.clockFontsize = val.size
          this.attrForm.formData.clockFontColor = val.color
          this.attrForm.formData.clockFont = val.font
          this.attrForm.formData.clockTimeFormat = val.format
          this.attrForm.formData.clockModel = val.mode
        }else if(item.weatherAttr) {
          val = item.weatherAttr[0]
          if(val) {
            this.attrForm.formData.province = val.province
            this.attrForm.formData.city = val.city
            this.attrForm.formData.weatherStyle = val.style
            this.attrForm.formData.switchTime = val.switchTime
            this.updateSelectedWidget(val.url, 7)
          }
        }else if(item.timerAttr) {
          val = item.timerAttr
          this.attrForm.formData.timerType = val.type
          this.attrForm.formData.link = val.mode
          this.attrForm.formData.timerFont = val.font
          this.attrForm.formData.timerFontsize = val.size
          this.attrForm.formData.timerFontColor = val.color
          this.attrForm.formData.timerEndDate = val.endDate
          this.attrForm.formData.timerEndTime = val.endTime
        }
      })
    },
    // 更改属性
    changeAttr(attr, val) {
      switch(attr){
        // 改Z轴
        case 'zindex':
          this.attrForm.formData.Z = val
          this.updateSelectedWidget(val, 1)
          break
        // 改背景
        case 'bgimage':
          this.attrForm.formData.bgfile = val
          this.updateSelectedWidget(val, 2)
          break
        // 改X坐标
        case 'xposition':
          this.attrForm.formData.X = Number(val)
          this.updateSelectedWidget(val, 3)
          break
        // 改Y坐标
        case 'yposition':
          this.attrForm.formData.Y = Number(val)
          this.updateSelectedWidget(val, 4)
          break
        // 改宽度
        case 'wid':
          this.attrForm.formData.W = Number(val)
          this.updateSelectedWidget(val, 5)
          break
        // 改高度
        case 'hei':
          this.attrForm.formData.H = Number(val)
          this.updateSelectedWidget(val, 6)
          break
        case 'rwidth':
          this.templateOpts.width = val
          break
        case 'rheight':
          this.templateOpts.height = val
          break
        // 改天气
        case 'weather':
          this.updateSelectedWidget(val, 7)
          break
        //新增天气属性
        case 'weatherAttr':
          this.updateSelectedWidget(val, 8)
          this.attrForm.formData.weatherAttr = val
          break
        // 改时钟属性
        case 'clock':
          this.attrForm.formData.clockFontsize = val.size
          this.attrForm.formData.clockFontColor = val.color
          this.attrForm.formData.clockFont = val.font
          this.attrForm.formData.clockTimeFormat = val.format
          this.attrForm.formData.clockModel = val.mode
          this.updateSelectedWidget(val, 9)
          break
        // 改时钟类型
        case 'clock-model':
          this.updateSelectedWidget(val, 11)
          break
        // 改计时器属性
        case 'timer':
          this.attrForm.formData.timerType = val.type
          this.attrForm.formData.link = val.mode
          this.attrForm.formData.timerFont = val.font
          this.attrForm.formData.timerFontsize = val.size
          this.attrForm.formData.timerFontColor = val.color
          this.attrForm.formData.timerEndDate = val.endDate
          this.attrForm.formData.timerEndTime = val.endTime
          this.updateSelectedWidget(val, 10)
          break
        // 改名称
        case 'name':
          this.attrForm.formData.name = val
          this.updateSelectedWidget(val, 12)
          break
        // 改背景值
        case 'bgimageId':
          this.attrForm.formData.mediaId = val
          break
        // 主播区avl
        case 'anchorAvl':
          this.attrForm.formData.anchorAvl = val
          this.updateSelectedWidget(val, 13)
          break
        // 音频区avl
        case 'audioAvl':
          this.attrForm.formData.audioAvl = val
          this.updateSelectedWidget(val, 13)
          break
        // 综合区avl
        case 'videoAvl':
          this.attrForm.formData.videoAvl = val
          this.updateSelectedWidget(val, 13)
          break
      }
    },
    // 模板类型选择
    async changeResolution(data) {
      console.log('changeResolution : ', data)
      const res = await this.doChangeResolution(data)
      if (res) {
        this.twidget = null
        this.templateOpts = {
          width: data.split('*')[0],
          height: data.split('*')[1]
        }
        this.attrForm.formData.width = data.split('*')[0]
        this.attrForm.formData.height = data.split('*')[1]
        this.showResolution()
      }
    },
    showResolution() {
      this.attrForm.formData.title = '模板'
      this.attrForm.showArea = 'main'
    },
    // 保存模板
    async doSubmitPreCheck() {
        var name = $('#name').val();
        if (name === '') {
            this.$message.error('请填写模板名称')
            return
        }
        const p = /^[[A-Za-z0-9\u4e00-\u9fa5]+$/
        if(!p.test(name)) {
          this.$message.error('模板名称输入不合法')
          return
        }
        if (this.widgetData.isEmpty()) {
            this.$message.error('请添加组件')
            return
        }
        let isAnchor = true
        let isRepeat = true
        let avlMap = new HashMap();
        let repeatValue = 0
        let widCount = 0
        this.widgetData.values().forEach(item => {
          if(item.type === 'Main' || item.type === 'Mixed' || item.type === 'Audio'){
            widCount = widCount + 1
            if(avlMap.containsKey(item.avl)) {
              isRepeat = false
              repeatValue = item.avl ? item.avl : 0
              return
            }
            avlMap.put(item.avl, item.avl)
          }
          if(item.type === 'Main'){
            isAnchor = false
            return
          }
        })
        if(widCount > 4) {
          this.$message.error('主播区,综合区,音频区总数不能超过4个')
          return
        }
        // if(!isRepeat) {
        //   this.$message.error('音频输出优先级['+repeatValue+']不能重复!')
        //   return
        // }
        if(isAnchor) {
          this.$message.error('请添加主播区组件')
          return
        }
        if (this.loading === null) {
          this.loading = this.$loading({ fullscreen: true, text: '模板保存中...' })
        }
        const refCount = this.attrForm.formData.refCount
        let cascade = 0
        const id = this.attrForm.formData.id
        if(refCount > 0 && id > 0) {
          const res = await this.$confirm('提示', '模板已被使用,需要级联更新否?')
          if(res) {
            cascade = 1
          }
        }
        setTimeout(() => {
          this.realCommit(name, cascade);
        }, 500);
    },
    realCommit(name, cascade) {
      let _this = this
      html2canvas(this.$refs.capture, {useCORS: true, allowTaint: true, taintTest: false}).then(function (canvas) {
          var imgUri = canvas.toDataURL('image/png').replace('data:image/png;base64,', '');
          let saveData = {}
          saveData.id = _this.attrForm.formData.id
          saveData.name = name
          saveData.cascadeUpdate = cascade
          saveData.thumbnailFile = imgUri
          saveData.mediaId = _this.attrForm.formData.mediaId ? _this.attrForm.formData.mediaId : 0
          saveData.folderId = _this.folderId ? _this.folderId : 0
          if(_this.ownerUserId) {
            saveData.ownerUserId = _this.ownerUserId
          }
          saveData.type = _this.attrForm.formData.width + '*' + _this.attrForm.formData.height
          saveData.width = _this.attrForm.formData.width
          saveData.height = _this.attrForm.formData.height
          saveData.argus = _this.widgetData.values()
          saveData.revision = _this.attrForm.formData.revision ? _this.attrForm.formData.revision : 0
          console.log('saveData : ', saveData, saveData.argus)
          _this.$emit('save', saveData)
          if (_this.loading) {
              _this.loading.close()
              _this.loading = null;
          }
      });
    },
    addWidgetInfo(item) {
      if(this.attrForm.formData.refCount > 0) {
        this.$alert('提示', '模板已被使用,不允许添加组件')
        return
      }
      this.initNeedAddWidgetInfo(item.prop, this.maxavl)
      if(item.prop === 'Main' || item.prop === 'Mixed' || item.prop === 'Audio'){
        if(this.maxavl > 0) {
          this.maxavl = this.maxavl - 1
        }
      }
    },
    originalSize() {
      const wid = this.templateOpts.width
      const hei = this.templateOpts.height
      this.originalTemplateSize(wid, hei, true)
      this.iwidthPercent = 1
      this.iheightPercent = 1
      this.originalState = true
    },
    reductionSize() {
      let ratio
      let wrapRatio = this.templateOpts.width / this.templateOpts.height
      let wid
      let hei
      if(wrapRatio > 1) {
        ratio = this.wrapperWidth / this.templateOpts.width
        wid = this.wrapperWidth
        hei = Math.round(this.templateOpts.height * ratio)
      }else if(wrapRatio < 1) {
        ratio = this.wrapperHeight / this.templateOpts.height
        wid =  Math.round(this.templateOpts.width * ratio)
        hei = this.wrapperHeight
      } else {
        ratio = this.wrapperWidth / this.templateOpts.width
        wid = this.wrapperWidth
        hei = this.wrapperHeight
      }
      this.iwidthPercent = ratio
      this.iheightPercent = ratio
      this.originalTemplateSize(wid, hei, false)
      this.originalState = false
    }
  }
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';
.addWiget {
  display: flex;
  justify-content: space-around;
  align-items: center;
  border-bottom: 1px solid $bg-e9;
  height: 48px;
}
.addWiget:hover {
  background-color: $defaultBlue;
  color:#fff;
}
.notclick {
  display: flex;
  justify-content: space-around;
  align-items: center;
  // text-decoration: line-through;
  border-bottom: 1px solid $bg-e9;
  height: 48px;
  pointer-events: none;
  filter: grayscale(10%);
  color: #ddd;
}
// .comWidget{
//     width: 200px;
//     height: 200px;
//     position:absolute;
//     border-style: solid;
//     border-width: 1px;
//     opacity:0.6;
//     filter:alpha(opacity=35);
// }
// .comWidget:hover{
//     border-color: gray;
//     box-shadow: 5px 5px 5px #aaaaaa;
// }

.template-main-wrapper {
  // border: 1px solid $bg-e9;
  position: relative;
  .compont {
    background: $bg-f4;
  }
}
.template-main-wrapper-original {
  // border: 1px solid $bg-e9;
  position: relative;
  overflow: auto;
  .compont {
    background: $bg-f4;
  }
}
</style>